<template>
  <div class="account-config-list">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-wrapper">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/accounts' }">账号列表</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/accounts/edit/${accountId}` }">编辑账号</el-breadcrumb-item>
        <el-breadcrumb-item>配置管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h3>账号配置管理</h3>
        <p>{{ accountName }} 的专属配置</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建配置
        </el-button>
        <el-button @click="handleCreateFromGlobal">
          <el-icon><DocumentCopy /></el-icon>
          从全局配置创建
        </el-button>
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-form :model="queryForm" inline>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="全部状态" clearable @change="handleQuery">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 配置表格 -->
    <el-table
      v-loading="accountConfigStore.loading"
      :data="accountConfigStore.configs"
      stripe
      class="config-table">

      <el-table-column prop="configName" label="配置名称" min-width="150">
        <template #default="{ row }">
          <div class="config-name">
            <span>{{ row.configName }}</span>
            <el-tag v-if="row.isActive === 1" type="success" size="small">激活</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="projectName" label="项目名称" width="120" />

      <el-table-column prop="baseAsset" label="基础资产" width="100" />

      <el-table-column prop="quoteAsset" label="报价资产" width="100" />

      <el-table-column prop="buyAmount" label="购买金额" width="120">
        <template #default="{ row }">
          <span>{{ formatAmount(row.buyAmount) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <StatusTag :value="row.status" :map="statusMap" />
        </template>
      </el-table-column>

      <el-table-column prop="updatedAt" label="更新时间" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.updatedAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            v-if="row.isActive !== 1"
            type="success"
            size="small"
            @click="handleActivate(row)">
            激活
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="handleViewHistory(row)">
            历史
          </el-button>
          <el-button
            type="warning"
            size="small"
            @click="handleViewTradeLogs(row)">
            日志
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange" />
    </div>

    <!-- 从全局配置创建对话框 -->
    <CreateFromGlobalDialog
      v-model:visible="showCreateFromGlobalDialog"
      :account-id="accountId"
      @success="handleCreateSuccess" />

    <el-dialog
      v-model="showHistoryDialog"
      :title="`${accountName} - ${historyConfigName} 历史记录`"
      width="720px">
      <div v-loading="historyLoading" class="history-content">
        <el-empty v-if="!historyRecords.length && !historyLoading" description="暂无历史记录" />
        <el-timeline v-else>
          <el-timeline-item
            v-for="item in historyRecords"
            :key="item.id"
            :timestamp="formatDateTime(item.createdAt)"
            placement="top">
            <div class="history-item">
              <strong>{{ formatOperationType(item.operationType) }}</strong>
              <p>{{ item.changeSummary }}</p>
            </div>
            <el-collapse>
              <el-collapse-item title="查看详情">
                <el-row :gutter="12">
                  <el-col :span="12">
                    <el-text type="info">旧配置</el-text>
                    <pre class="history-json">{{ item.oldConfig }}</pre>
                  </el-col>
                  <el-col :span="12">
                    <el-text type="info">新配置</el-text>
                    <pre class="history-json">{{ item.newConfig }}</pre>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
          </el-timeline-item>
        </el-timeline>
      </div>
      <template #footer>
        <div class="history-footer">
          <el-pagination
            v-model:current-page="historyPagination.page"
            :page-size="historyPagination.size"
            :total="historyPagination.total"
            layout="prev, pager, next"
            @current-change="handleHistoryPageChange" />
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showTradeLogDialog"
      :title="`${accountName} - ${tradeLogConfigName} 交易日志`"
      width="860px">
      <div v-loading="tradeLogLoading" class="trade-log-content">
        <el-empty v-if="!tradeLogs.length && !tradeLogLoading" description="暂无交易日志" />
        <el-table v-else :data="tradeLogs" size="small">
          <el-table-column prop="tradeTime" label="时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.tradeTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="direction" label="方向" width="100" />
          <el-table-column prop="plannedAmount" label="计划额度">
            <template #default="{ row }">{{ formatAmount(row.plannedAmount) }}</template>
          </el-table-column>
          <el-table-column prop="actualAmount" label="实际额度">
            <template #default="{ row }">{{ formatAmount(row.actualAmount) }}</template>
          </el-table-column>
          <el-table-column prop="slippage" label="磨损">
            <template #default="{ row }">{{ formatAmount(row.slippage) }}</template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" />
          <el-table-column prop="txHash" label="交易哈希" min-width="160" show-overflow-tooltip />
        </el-table>
      </div>
      <template #footer>
        <div class="history-footer">
          <el-pagination
            v-model:current-page="tradeLogPagination.page"
            :page-size="tradeLogPagination.size"
            :total="tradeLogPagination.total"
            layout="prev, pager, next"
            @current-change="handleTradeLogPageChange" />
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAccountConfigStore } from '@/store/accountConfig'
import { ElMessageBox, ElMessage } from 'element-plus'
import { http } from '@/utils/request'
import StatusTag from '@/components/StatusTag.vue'
import CreateFromGlobalDialog from '@/components/CreateFromGlobalDialog.vue'
import { useTradeLogStore } from '@/store/tradeLog'

const route = useRoute()
const router = useRouter()
const accountConfigStore = useAccountConfigStore()
const tradeLogStore = useTradeLogStore()

// 获取路由参数
const accountId = ref(parseInt(route.params.accountId))
const accountName = ref('') // 从账号信息获取

// 查询表单
const queryForm = reactive({
  status: null
})

// 分页
const pagination = computed(() => accountConfigStore.pagination)

// 对话框状态
const showCreateFromGlobalDialog = ref(false)
const showHistoryDialog = ref(false)
const historyLoading = ref(false)
const historyRecords = ref([])
const historyPagination = reactive({
  page: 1,
  size: 10,
  total: 0
})
const historyConfigName = ref('')
const historyConfigId = ref(null)

const showTradeLogDialog = ref(false)
const tradeLogLoading = ref(false)
const tradeLogs = ref([])
const tradeLogPagination = reactive({
  page: 1,
  size: 10,
  total: 0
})
const tradeLogConfigName = ref('')
const tradeLogConfigId = ref(null)

const statusMap = {
  1: { text: '启用', type: 'success' },
  0: { text: '禁用', type: 'danger' }
}

// 初始化页面
onMounted(async () => {
  await Promise.all([loadAccountName(), loadConfigs()])
})

const loadAccountName = async () => {
  try {
    const response = await http.get(`/accounts/${accountId.value}`)
    accountName.value = response.data.name
  } catch (error) {
    accountName.value = `账号${accountId.value}`
  }
}

// 加载配置列表
const loadConfigs = async () => {
  try {
    await accountConfigStore.fetchAccountConfigs(accountId.value, {
      page: pagination.value.page,
      size: pagination.value.size,
      status: queryForm.status
    })
  } catch (error) {
    ElMessage.error('加载配置列表失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.value.page = 1
  loadConfigs()
}

// 重置
const handleReset = () => {
  queryForm.status = null
  handleQuery()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.value.page = page
  loadConfigs()
}

const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.page = 1
  loadConfigs()
}

// 新建配置
const handleCreate = () => {
  router.push(`/accounts/${accountId.value}/configs/edit`)
}

// 从全局配置创建
const handleCreateFromGlobal = () => {
  showCreateFromGlobalDialog.value = true
}

// 编辑配置
const handleEdit = (row) => {
  router.push(`/accounts/${accountId.value}/configs/edit/${row.id}`)
}

// 激活配置
const handleActivate = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要激活配置 "${row.configName}" 吗？这将停用该账号的其他配置。`,
      '确认激活',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await accountConfigStore.activateAccountConfig(accountId.value, row.id)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('激活配置失败')
    }
  }
}

// 删除配置
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置 "${row.configName}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await accountConfigStore.deleteAccountConfig(accountId.value, row.id)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除配置失败')
    }
  }
}

// 查看历史
const handleViewHistory = async (row) => {
  historyConfigName.value = row.configName
  historyConfigId.value = row.id
  historyPagination.page = 1
  await loadHistory(row.id)
  showHistoryDialog.value = true
}

const loadHistory = async (configId) => {
  historyLoading.value = true
  try {
    const response = await accountConfigStore.getAccountConfigHistory(accountId.value, configId, {
      page: historyPagination.page,
      size: historyPagination.size
    })
    const { list, total } = response
    historyRecords.value = list || []
    historyPagination.total = total || 0
  } catch (error) {
    ElMessage.error('加载历史记录失败')
  } finally {
    historyLoading.value = false
  }
}

const handleHistoryPageChange = async (page) => {
  historyPagination.page = page
  if (historyConfigId.value) {
    await loadHistory(historyConfigId.value)
  }
}

const handleViewTradeLogs = async (row) => {
  tradeLogConfigName.value = row.configName
  tradeLogConfigId.value = row.id
  tradeLogPagination.page = 1
  await loadTradeLogs()
  showTradeLogDialog.value = true
}

const loadTradeLogs = async () => {
  if (!tradeLogConfigId.value) return
  tradeLogLoading.value = true
  try {
    const response = await tradeLogStore.fetchTradeLogs({
      accountId: accountId.value,
      accountConfigId: tradeLogConfigId.value,
      page: tradeLogPagination.page,
      size: tradeLogPagination.size
    })
    tradeLogs.value = response.list || []
    tradeLogPagination.total = response.total || 0
    tradeLogPagination.page = response.page || 1
    tradeLogPagination.size = response.size || tradeLogPagination.size
  } catch (error) {
    ElMessage.error('加载交易日志失败')
  } finally {
    tradeLogLoading.value = false
  }
}

const handleTradeLogPageChange = async (page) => {
  tradeLogPagination.page = page
  await loadTradeLogs()
}

// 创建成功回调
const handleCreateSuccess = () => {
  showCreateFromGlobalDialog.value = false
  loadConfigs()
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatOperationType = (type) => {
  if (!type) return '操作'
  const map = {
    CREATE: '创建',
    UPDATE: '更新',
    DELETE: '删除'
  }
  return map[type] || type
}
</script>

<style lang="scss" scoped>
.account-config-list {
  .breadcrumb-wrapper {
    margin-bottom: 15px;
    padding: 12px 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-left {
      h3 {
        margin: 0 0 5px;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }

    .header-right {
      .el-button + .el-button {
        margin-left: 10px;
      }
    }
  }

  .filter-bar {
    margin-bottom: 20px;
    padding: 15px 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .config-table {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .config-name {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .history-content {
    max-height: 420px;
    overflow-y: auto;

    .history-item {
      margin-bottom: 8px;
    }

    .history-json {
      padding: 10px;
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 4px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 12px;
      white-space: pre-wrap;
      word-break: break-word;
    }
  }

  .history-footer {
    display: flex;
    justify-content: center;
  }

  .trade-log-content {
    max-height: 420px;
    overflow-y: auto;
  }
}
</style>
